package com.hc.kotlin_coroutine

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.fold
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.reduce
import kotlinx.coroutines.flow.sample
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        println("------map------")
        val flow1 = flowOf(1,2,3,4,5)
        flow1.map {
            it * it
        }.collect{
            println(it)
        }
        println("------filter------")
        val flow2 = flowOf(1,2,3,4,5)
        flow2.filter {
            it > 2
        }.map {
            it * it
        }.collect {
            println(it)
        }
        println("------onEach------")
        val flow3 = flowOf(1,2,3,4,5)
        flow3.onEach {
            println(it)
        }.collect{

        }
        println("------debounce------")
        val flow4 = flow {
            emit(1)
            emit(2)
            delay(1000)
            emit(3)
            delay(500)
            emit(4)
            delay(500)
            emit(5)
        }
        .debounce(800)
        .collect{
            println(it)
        }
        println("------sample------")
//        val flow5 = flow {
//            while (true){
//                emit("发送一条消息")
//            }
//        }
//        .sample(1000)
//        .flowOn(Dispatchers.IO)
//        .collect{
//            println(it)
//        }
        println("------reduce------")
        val flow6 = flow {
            for (i in (1..100)){
                emit(i)
            }
        }.reduce{ total,current->
            total + current
        }
        println(flow6)
        println("------fold------")
        val flow7 = flow {
            for (i in ('a'..'z')){
                emit(i)
            }
        }.fold("Name is:") {total,current->
            total+current
        }
        println(flow7)
    }
}